package com.dongdongshop.controller;

import cn.hutool.json.JSONUtil;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnums;
import com.dongdongshop.pojo.TbContent;
import com.dongdongshop.service.TbContentService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("TbContent")
public class TbContentController {

    //注入service
    @DubboReference
    private TbContentService tbContentService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询数据(按照分类,降序,有效)
    @ResponseBody
    @RequestMapping("showTbContentbycategoryId")
    public Result showTbContentbycategoryId(Integer categoryId) {
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String o = (String)valueOperations.get("shuju" + categoryId);
            if (o == null){
                List<TbContent> list = tbContentService.showTbContentbycategoryId(categoryId);
                valueOperations.set("shuju"+categoryId,JSONUtil.toJsonStr(list));
                return Result.response(ResultEnums.SHOW_SUCCESS).setData(list);
            }else {
                List<TbContent> tbContents = JSONUtil.toList(o, TbContent.class);
                return Result.response(ResultEnums.SHOW_SUCCESS).setData(tbContents);
            }
        }catch (Exception e){
            System.out.println(e);
            return Result.response(ResultEnums.SHOW_ERROR);
        }
    }
}
